﻿//======================================================
//==     (c)2008 古羌科技 by NeTCMS v1.0              ==
//==          Forum:bbs.aspxcms.com                   ==
//==         Website:www.aspxcms.com                  ==
//======================================================
using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.Text.RegularExpressions;
using AMG.Config;
using System.Collections.Generic;
using System.Text;
namespace AMG.Common
{
    /// <summary>
    /// 公用类
    /// </summary>
    public class Public
    {

        /// <summary>
        /// 取得用户客户端IP(穿过代理服务器取远程用户真实IP地址)
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            try
            {
                if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
                else
                    return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            catch { return ""; }
            //return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        }
        /// <summary>
        /// 取得前一个（上次提交或链接进来的）网页的URL
        /// </summary>
        /// <returns></returns>
        public static string GetReferrerUrl()
        {
            Uri uri = HttpContext.Current.Request.UrlReferrer;
            if (uri != null)
                return uri.ToString();
            else
                return string.Empty;
        }
        /// <summary>
        /// 去除字符串最后一个','号
        /// </summary>
        /// <param name="chr">:要做处理的字符串</param>
        /// <returns>返回已处理的字符串</returns>
        /// CreateTime:2007-03-26 Code By DengXi
        public static string Lost(string chr)
        {
            if (chr == null || chr == string.Empty)
            {
                return "";
            }
            else
            {
                chr = chr.Remove(chr.LastIndexOf(","));
                return chr;
            }
        }

        //  
        public static string lostfirst(string chr)
        {
            string flg = "";
            if (chr != string.Empty || chr != null)
            {
                if (chr.Substring(0, 1) == "/")
                    flg = chr.Replace(chr.Substring(0, 1), "");
                else
                    flg = chr;
            }
            return flg;
        }

        /// <summary>
        /// 取得文件扩展名
        /// </summary>
        /// <param name="filename">文件名</param>
        /// <returns>扩展名</returns>
        public static string getFileExtName(string filename)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return "";
            }
            if (filename.IndexOf(@".") == -1)
            {
                return "";
            }
            int pos = -1;
            if (!(filename.IndexOf(@"\") == -1))
            {
                pos = filename.LastIndexOf(@"\");
            }
            string[] s = filename.Substring(pos + 1).Split('.');
            return s[1];
        }


        /// <summary>
        /// web.config相关文件操作
        /// 0检测是web.config是否为只读或可写;返回值为:true或false,1把web.config改写为只读;2把web.config改写为可写
        /// 在此函数中自动去根目下寻找web.config
        /// </summary>
        /// <param name="flg">0检测是web.config是否为只读或可写;返回值为:true或false,1把web.config改写为只读;2把web.config改写为可写</param>
        /// 2007-5-9 y.xiaobin
        /// <returns></returns>
        public static bool constReadOnly(int num)
        {
            bool _readonly = false;
            string _config = HttpContext.Current.Server.MapPath(@"~/Web.config");
            FileInfo fi = new FileInfo(_config);
            switch (num)
            {
                case 0: _readonly = fi.IsReadOnly; break;
                case 1:
                    fi.IsReadOnly = true;
                    _readonly = true;
                    break;
                case 2:
                    {
                        fi.IsReadOnly = false;
                        _readonly = false;
                    }
                    break;
                default: throw new Exception("错误参数!");
            }

            return _readonly;

        }

        /// <summary>
        /// web.config相关文件操作
        /// 0检测是web.config是否为只读或可写;返回值为:true或false,1把config改写为只读;2把web.config改写为可写
        /// 在此函数中自动去根目下寻找web.config
        /// </summary>
        /// <param name="flg">0检测是web.config是否为只读或可写;返回值为:true或false,1把web.config改写为只读;2把web.config改写为可写</param>
        /// 2007-5-9 y.xiaobin
        /// <returns></returns>
        public static bool constReadOnly(int num, string strSource)
        {
            bool _readonly = false;
            string _config = HttpContext.Current.Server.MapPath(@"~/" + strSource);
            FileInfo fi = new FileInfo(_config);
            switch (num)
            {
                case 0: _readonly = fi.IsReadOnly; break;
                case 1:
                    fi.IsReadOnly = true;
                    _readonly = true;
                    break;
                case 2:
                    {
                        fi.IsReadOnly = false;
                        _readonly = false;
                    }
                    break;
                default: throw new Exception("错误参数!");
            }

            return _readonly;

        }
        /// <summary>
        /// 保存web.config设置
        /// </summary>
        /// <param name="xmlTargetElement">关键字</param>
        /// <param name="xmlText">value</param>
        /// 2007.05.09 修改 y.xiaobin
        public static void SaveXmlElementValue(string xmlTargetElement, string xmlText)
        {
            string returnInt = null;
            string filename = HttpContext.Current.Server.MapPath("~") + @"/Web.config";
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.Load(filename);
            XmlNodeList topM = xmldoc.DocumentElement.ChildNodes;
            foreach (XmlNode element in topM)
            {
                if (element.Name == "appSettings")
                {
                    XmlNodeList node = element.ChildNodes;
                    if (node.Count > 0)
                    {
                        foreach (XmlNode el in node)
                        {
                            if (el.Name == "add")
                            {
                                if (el.Attributes["key"].InnerXml == xmlTargetElement)
                                {
                                    //保存web.config数据
                                    el.Attributes["value"].Value = xmlText;
                                    xmldoc.Save(HttpContext.Current.Server.MapPath(@"~/Web.config"));
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        returnInt = "Web.Config配置文件未配置";
                    }
                    break;
                }
                else
                {
                    returnInt = "Web.Config配置文件未配置";
                }
            }

            if (returnInt != null)
                throw new Exception(returnInt);
        }

        /// <summary>
        /// 生成XML文件
        /// </summary>
        /// <param name="Ename"></param>
        public static void saveClassXML(string Ename)
        {
            StreamWriter sw = null;

            {
                string FileName = HttpContext.Current.Server.MapPath("~/xml/Content/" + Ename + ".xml");
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/xml/Content")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/xml/Content"));
                }
                sw = File.CreateText(FileName);
                sw.WriteLine("<?xml version=\"1.0\" encoding=\"gb2312\"?>\r");
                sw.WriteLine("<rss version=\"2.0\">\r");
                sw.WriteLine("<channel>\r");
                sw.WriteLine("<item>\r");
                sw.WriteLine("</item>\r");
                sw.WriteLine("</channel>\r");
                sw.WriteLine("</rss>\r");
                sw.Flush();
                sw.Close(); sw.Dispose();
            }
        }

        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="strTarget">接点名</param>
        /// <returns></returns>
        public static string readparamConfig(string strTarget)
        {
            string rstr = "";
            string xmlPath = HttpContext.Current.Server.MapPath("~/xml/sys/base.config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            rstr += elemList[0].InnerXml;
            return rstr;
        }

        /// <summary>
        /// 读取IM配置
        /// </summary>
        /// <param name="strTarget">接点名</param>
        /// <returns></returns>
        public static string readIMConfig(string strTarget)
        {
            string rstr = "";
            string xmlPath = HttpContext.Current.Server.MapPath("~/config/im.config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            rstr += elemList[0].InnerXml;
            return rstr;
        }


        /// <summary>
        /// 读取频道配置
        /// </summary>
        public static string readCHparamConfig(string strTarget, int ChID)
        {
            string rstr = "";
            string xmlPath = HttpContext.Current.Server.MapPath("~/xml/sys/Channel/ChParams/CH_" + ChID.ToString() + ".config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            rstr += elemList[0].InnerXml;
            return rstr;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        /// <param name="strTarget">接点名</param>
        /// <returns></returns>
        public static void SaveXmlConfig(string strTarget, string strValue, string strSource)
        {
            string xmlPath = HttpContext.Current.Server.MapPath("~/" + strSource);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName(strTarget);
            elemList[0].InnerXml = strValue;
            xdoc.Save(xmlPath);
        }

        /// <summary>
        /// 读取配置
        /// </summary>
        /// <param name="strTarget">接点名</param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static string readparamConfig(string strTarget, string type)
        {
            string rstr = "";
            if (type != null && type != string.Empty)
            {
                string xmlPath = HttpContext.Current.Server.MapPath("~/xml/sys/" + type + ".config");
                FileInfo finfo = new FileInfo(xmlPath);
                System.Xml.XmlDocument xdoc = new XmlDocument();
                xdoc.Load(xmlPath);
                XmlElement root = xdoc.DocumentElement;
                XmlNodeList elemList = root.GetElementsByTagName(strTarget);
                rstr += elemList[0].InnerXml;
            }
            else
            {
                rstr = readparamConfig(strTarget);
            }
            return rstr;
        }

        public static void saveLogFiles(int _num, string UserNum, string Title, string Content)
        {
            StreamWriter sw = null;
            DateTime date = DateTime.Now;
            string FileName = date.Year + "-" + date.Month;
            try
            {
                FileName = HttpContext.Current.Server.MapPath("~/Logs/User-" + _num + "-") + FileName + "-";// +NetCMS.Common.Input.MD5(FileName) + "-s.log";

                #region 检测日志目录是否存在
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Logs")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Logs"));
                }

                if (!File.Exists(FileName))
                    sw = File.CreateText(FileName);
                else
                {
                    sw = File.AppendText(FileName);
                }
                #endregion

                //sw.WriteLine("IP                 :" + NetCMS.Common.Public.getUserIP() + "\r");
                sw.WriteLine("title              :" + Title + "\r");
                sw.WriteLine("content            :" + Content);
                sw.WriteLine("usernum&UserName   :" + UserNum + "\r");
                sw.WriteLine("Time               :" + System.DateTime.Now);
                sw.WriteLine("≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡\r");
                sw.Flush();
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }
        }

        /// <summary>
        /// 插入积分记录
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="Point"></param>
        /// <param name="Flag">0增加，1减少</param>
        public static void SaveInLogs(int UserID, int Point, int Flag, string Content)
        {
            StreamWriter sw = null;
            DateTime date = DateTime.Now;
            string FileName = date.Year + "-" + date.Month;
            try
            {
                FileName = HttpContext.Current.Server.MapPath("~/Logs/integral/" + UserID + "," + FileName + ".log");

                #region 检测日志目录是否存在
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Logs")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Logs"));
                }

                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Logs/integral")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Logs/integral"));
                }

                if (!File.Exists(FileName))
                    sw = File.CreateText(FileName);
                else
                {
                    sw = File.AppendText(FileName);
                }
                #endregion
                sw.WriteLine("IP :" + AMG.Common.Public.GetClientIP() + "\r");
                sw.WriteLine("用户ID :" + UserID + "\r");
                sw.WriteLine("积分、金币:" + Point);
                sw.WriteLine("增加还是减少 :" + Flag + "\r");
                sw.WriteLine("Time :" + System.DateTime.Now);
                sw.WriteLine("Content :" + Content);
                sw.WriteLine("≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡\r");
                sw.Flush();
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }
        }

        /// <summary>
        /// 发布日志
        /// </summary>
        /// <param name="item"></param>
        /// <param name="errorContent"></param>
        /// <param name="username"></param>
        public static void savePublicLogFiles(string item, string errorContent, string username)
        {
            StreamWriter sw = null;
            DateTime date = DateTime.Now;
            string FileName = "";// NetCMS.Config.UIConfig.Logfilename;
            try
            {
                FileName = HttpContext.Current.Server.MapPath("~/Logs/public/" + FileName + "_" + date.Month + date.Day + ".log");

                #region 检测日志目录是否存在
                if (!Directory.Exists(HttpContext.Current.Server.MapPath("~/Logs")))
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath("~/Logs"));
                }

                if (!File.Exists(FileName))
                {
                    sw = File.CreateText(FileName);
                }
                else
                {
                    sw = File.AppendText(FileName);
                }
                #endregion
                sw.WriteLine(item);
                sw.WriteLine(errorContent);
                sw.WriteLine("【UserName】" + username + "   【Time】" + System.DateTime.Now);
                sw.WriteLine("≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡≡\r");
                sw.Flush();
            }
            finally
            {
                if (sw != null)
                    sw.Close();
            }
        }


        /// <summary> 
        /// 汉字转拼音缩写 
        /// 2004-11-30 
        /// </summary> 
        /// <param name="Input">要转换的汉字字符串</param> 
        /// <returns>拼音缩写</returns> 
        public static string GetPYString(string Input)
        {
            string ret = "";
            foreach (char c in Input)
            {
                if ((int)c >= 33 && (int)c <= 126)
                {//字母和符号原样保留 
                    ret += c.ToString();
                }
                else
                {//累加拼音声母 
                    ret += GetPYChar(c.ToString());
                }
            }
            return ret;
        }

        /// <summary> 
        /// 取单个字符的拼音声母 
        /// 2004-11-30 
        /// </summary> 
        /// <param name="c">要转换的单个汉字</param> 
        /// <returns>拼音声母</returns> 
        private static string GetPYChar(string c)
        {
            byte[] array = new byte[2];
            array = System.Text.Encoding.Default.GetBytes(c);
            int i = (short)(array[0] - '\0') * 256 + ((short)(array[1] - '\0'));
            if (i < 0xB0A1) return "*";
            if (i < 0xB0C5) return "A";
            if (i < 0xB2C1) return "B";
            if (i < 0xB4EE) return "C";
            if (i < 0xB6EA) return "D";
            if (i < 0xB7A2) return "E";
            if (i < 0xB8C1) return "F";
            if (i < 0xB9FE) return "G";
            if (i < 0xBBF7) return "H";
            if (i < 0xBFA6) return "G";
            if (i < 0xC0AC) return "K";
            if (i < 0xC2E8) return "L";
            if (i < 0xC4C3) return "M";
            if (i < 0xC5B6) return "N";
            if (i < 0xC5BE) return "O";
            if (i < 0xC6DA) return "P";
            if (i < 0xC8BB) return "Q";
            if (i < 0xC8F6) return "R";
            if (i < 0xCBFA) return "S";
            if (i < 0xCDDA) return "T";
            if (i < 0xCEF4) return "W";
            if (i < 0xD1B9) return "X";
            if (i < 0xD4D1) return "Y";
            if (i < 0xD7FA) return "Z";
            return "*";
        }

        /// <summary>
        /// 获得样式
        /// </summary>
        /// <param name="formName">表单名</param>
        /// <param name="Dir">xml源</param>
        /// <returns></returns>
        /// by Simplt.xie
        public static string getxmlstylelist(string formName, string Dir)
        {
            string _Str = "<select style=\"width:150px;\" class=\"form\" name=\"" + formName + "\" onchange=\"javascript:getValue(this.value);\">\r";
            string xmlPath = HttpContext.Current.Server.MapPath(Dir);
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName("stylename");
            XmlNodeList elemList1 = root.GetElementsByTagName("stylevalue");
            for (int i = 0; i < elemList.Count; i++)
            {
                string _i = (i + 1).ToString();
                if (_i.Length < 2) { _i = "0" + _i; }
                _Str += "<option value=\"" + elemList1[i].InnerXml + "\">" + (_i) + ".&nbsp;" + elemList[i].InnerXml + "</option>\r";
            }
            _Str += "</select>\r";
            return _Str;
        }

        /// <summary>
        /// 读取模型配置
        /// </summary>
        /// <param name="Number"></param>
        /// <returns></returns>
        public static string getModelContentType(string Number)
        {
            string disable = string.Empty;
            if (Number.Trim() != "999")
            {
                disable = "disabled=\"disabled\"";
            }
            string _Str = "<select " + disable + " style=\"width:310px;\" class=\"form\" name=\"channelType\">\r";
            string xmlPath = HttpContext.Current.Server.MapPath("~/xml/sys/channel/channelbase.config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName("channelNumber");
            XmlNodeList elemList1 = root.GetElementsByTagName("channelName");
            for (int i = 0; i < elemList.Count; i++)
            {
                if (Number == elemList[i].InnerXml)
                {
                    _Str += "<option value=\"" + elemList[i].InnerXml + "\" selected>" + elemList1[i].InnerXml + "</option>\r";
                }
                else
                {
                    _Str += "<option value=\"" + elemList[i].InnerXml + "\">" + elemList1[i].InnerXml + "</option>\r";
                }
            }
            _Str += "</select>\r";
            return _Str;
        }

        /// <summary>
        /// 读取模型类型默认的自定义字段
        /// </summary>
        /// <param name="Number"></param>
        /// <returns></returns>
        public static string getModelContentField(string Number)
        {
            string _Str = string.Empty;
            string xmlPath = HttpContext.Current.Server.MapPath("~/xml/sys/channel/channelbase.config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName("channelNumber");
            XmlNodeList elemList1 = root.GetElementsByTagName("channelvalue");
            for (int i = 0; i < elemList.Count; i++)
            {
                if (Number.Trim() == elemList[i].InnerXml.Trim())
                {
                    _Str = elemList1[i].InnerXml.Trim();
                    break;
                }
                else
                {
                    continue;
                }
            }
            return _Str;
        }

        /// <summary>
        /// 读取字段配置
        /// </summary>
        /// <param name="Number"></param>
        /// <returns></returns>
        public static string getValueType(string Number)
        {
            string disable = string.Empty;
            if (Number.Trim() != "999")
            {
                disable = "disabled=\"disabled\"";
            }
            string _Str = "<select " + disable + " style=\"width:280px;\" class=\"form\" name=\"vType\" onchange=\"javascript:getValue(this.value);\">\r";
            string xmlPath = HttpContext.Current.Server.MapPath("~/xml/sys/channel/value.config");
            FileInfo finfo = new FileInfo(xmlPath);
            System.Xml.XmlDocument xdoc = new XmlDocument();
            xdoc.Load(xmlPath);
            XmlElement root = xdoc.DocumentElement;
            XmlNodeList elemList = root.GetElementsByTagName("valuetype");
            XmlNodeList elemList1 = root.GetElementsByTagName("valueName");
            string istr = string.Empty;
            for (int i = 0; i < elemList.Count; i++)
            {

                if (i < 9)
                {
                    istr = "0" + (i + 1).ToString() + ".";
                }
                else
                {
                    istr = (i + 1).ToString() + ".";
                }
                if (Number == elemList[i].InnerXml)
                {
                    _Str += "<option value=\"" + elemList[i].InnerXml + "\" selected>" + istr + elemList1[i].InnerXml + "</option>\r";
                }
                else
                {
                    _Str += "<option value=\"" + elemList[i].InnerXml + "\">" + istr + elemList1[i].InnerXml + "</option>\r";
                }
            }
            _Str += "</select>\r";
            return _Str;
        }


        /// <summary>
        /// 检查当前IP是否是受限IP
        /// </summary>
        /// <param name="LimitedIP">受限的IP，格式如:192.168.1.110|212.235.*.*|232.*.*.*</param>
        /// <returns>返回true表示IP未受到限制</returns>
        static public bool ValidateIP(string LimitedIP)
        {
            string CurrentIP = GetClientIP();
            if (LimitedIP == null || LimitedIP.Trim() == string.Empty)
                return true;
            LimitedIP.Replace(".", @"\.");
            LimitedIP.Replace("*", @"[^\.]{1,3}");
            Regex reg = new Regex(LimitedIP, RegexOptions.Compiled);
            Match match = reg.Match(CurrentIP);
            return !match.Success;
        }

        /// <summary>
        /// 判断会员组
        /// </summary>
        /// <param name="uGroup"></param>
        /// <param name="nGroup"></param>
        /// <returns></returns>
        public static bool CommgetGroup(string uGroup, string nGroup)
        {
            bool gf = false;
            if (nGroup == string.Empty)
            {
                gf = true;
            }
            else
            {
                if (nGroup.IndexOf(".") > -1)
                {
                    string[] gARR = nGroup.Split(',');
                    for (int i = 0; i < gARR.Length; i++)
                    {
                        if (uGroup == gARR[i].ToString().Trim())
                        {
                            gf = true;
                        }
                    }
                }
                else
                {
                    if (uGroup == nGroup)
                    {
                        gf = true;
                    }
                }
            }
            return gf;
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="path">文件路径</param>
        public static void DelFile(string path)
        {
            try
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
            catch (IOException e) { }
        }
        
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="path">文件夹路径</param>
        public static void DelDir(string path)
        {
            try
            {
                if (Directory.Exists(path))
                {
                    Directory.Delete(path);
                }
            }
            catch (IOException e) { }
        }

        /// <summary>
        /// 取得与当前时间的间隔
        /// </summary>
        /// <param name="time1">原始时间</param>
        /// <returns></returns>
        public static string getTimeSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (second < 0) { second = 0; }
            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = second + "秒钟前";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("MM-dd hh:mm");
            }
            return strTime;
        }

        /// <summary>
        /// 取得与当前时间的间隔(不显示时分)
        /// </summary>
        /// <param name="time1">原始时间</param>
        /// <returns></returns>
        public static string getTimeEXSpan(DateTime time1)
        {
            string strTime = "";
            DateTime date1 = DateTime.Now;
            DateTime date2 = time1;
            TimeSpan dt = date1 - date2;

            // 相差天数
            int days = dt.Days;
            // 时间点相差小时数
            int hours = dt.Hours;
            // 相差总小时数
            double Minutes = dt.Minutes;
            // 相差总秒数
            int second = dt.Seconds;

            if (days == 0 && hours == 0 && Minutes == 0)
            {
                strTime = second + "秒钟前";
            }
            else if (days == 0 && hours == 0)
            {
                strTime = Minutes + "分钟前";
            }
            else if (days == 0)
            {
                strTime = hours + "小时前";
            }
            else
            {
                strTime = time1.ToString("MM-dd");
            }
            return strTime;
        }
        /// <summary>
        /// 获取时间相隔天数
        /// </summary>
        /// <param name="time1">时间1</param>
        /// <returns></returns>
        public static string getDaySpan(DateTime time1)
        {
            TimeSpan ts = DateTime.Now - time1;
            return ts.Days.ToString();
        }
        /// <summary>
        /// 读取并返回一个文本文件的内容
        /// </summary>
        /// <param name="filePath">文件的物理路径</param>
        /// <returns></returns>
        public static string GetTextFileContent(string filePath)
        {
            string result = string.Empty;
            if (File.Exists(filePath))
            {
                try
                {
                    using (StreamReader sr = new StreamReader(filePath))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                catch
                { }
            }
            return result;
        }

        /// <summary>
        /// 替换文本中的空格和换行
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string ReplaceSpace(string str)
        {
            string s = str;
            s = s.Replace(" ", "&nbsp;");
            s = s.Replace("\n", "<BR />");
            return s;
        }

        /// <summary>
        /// 过滤关键字，查看是否是禁用姓名
        /// </summary>
        /// <param name="key">关键字</param>
        /// <param name="flag">true：关键字 false：姓名</param>
        /// <returns></returns>
        public static string CheckKey(string key, bool flag)
        {
            string fg = "";
            string strKey = "";
            if (flag)
            {
                strKey = AMG.Config.SysConfig.KeyWord;
            }
            else
            {
                strKey = AMG.Config.SysConfig.UserName;
            }

            string[] Str = strKey.Split('|');
            for (int i = 0; i < Str.Length; i++)
            {
                try
                {
                    if (key.Contains(Str[i].ToString()))
                    {
                        fg = Str[i].ToString();
                        break;
                    }
                }
                catch { }
            }
            return fg;
        }

        /// <summary>
        /// 读取模板内容
        /// </summary>
        /// <param name="path">模板路径</param>
        /// <returns></returns>
        public static string getTempleContent(string path)
        {
            string result = string.Empty;
            string sFileName = HttpContext.Current.Server.MapPath(path);
            if (File.Exists(sFileName))
            {
                try
                {
                    using (StreamReader sr = new StreamReader(sFileName))
                    {
                        result = sr.ReadToEnd();
                    }
                }
                catch
                { }
            }
            else
            {
                result = "模板不存在!";
            }
            return result;
        }

        /// <summary>
        /// 读取,添加，修改xml文件
        /// </summary>
        /// <param name="Xmlpath">Xml路径</param>
        /// <param name="Node">新的子节点名称</param>
        /// <param name="Value">新节点对应的值</param>
        /// <param name="flag">1：读取，否则为 修改或者添加</param>
        /// <returns>1：修改添加成功，为空字符串表示修改添加成功，否则是读取成功</returns>
        static public string getXML(string Xmlpath, string Node, string Value, int flag)
        {
            try
            {
                string filepath = HttpContext.Current.Server.MapPath(Xmlpath);
                XmlDocument xmlDoc = new XmlDocument();
                if (!File.Exists(filepath))
                {
                    if (flag == 1)
                    {
                        return string.Empty;
                    }
                    else
                    {//创建XML
                        XmlDeclaration xn = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);
                        XmlElement root = xmlDoc.CreateElement("rss");
                        XmlElement root1 = xmlDoc.CreateElement("item");

                        root.AppendChild(root1);
                        xmlDoc.AppendChild(xn);
                        xmlDoc.AppendChild(root);
                        xmlDoc.Save(filepath);//本地路径名字
                    }
                }
                xmlDoc.Load(filepath);//你的xml文件
                string ReStr = "";
                XmlElement xmlObj = xmlDoc.DocumentElement;

                XmlNodeList xmlList = xmlDoc.SelectSingleNode(xmlObj.Name.ToString()).ChildNodes;

                foreach (XmlNode xmlNo in xmlList)
                {
                    if (xmlNo.NodeType != XmlNodeType.Comment)//判断是不是注释类型
                    {
                        XmlElement xe = (XmlElement)xmlNo;
                        {
                            if (xe.Name == xmlObj.FirstChild.Name)
                            {
                                XmlNodeList xmlNList = xmlObj.FirstChild.ChildNodes;

                                foreach (XmlNode xmld in xmlNList)
                                {
                                    XmlElement xe1 = (XmlElement)xmld;
                                    {
                                        if (xe1.Name == Node)
                                        {
                                            if (flag == 1)//读取值
                                            {
                                                if (xmld.InnerText != null && xmld.InnerText != "")
                                                {
                                                    ReStr += xmld.InnerText;
                                                }
                                            }
                                            else//修改值
                                            {
                                                xmld.InnerText = Value;//给节点赋值
                                                xmlDoc.Save(filepath);
                                                ReStr = "9999999999999999999";
                                            }
                                        }
                                    }
                                }
                                if (ReStr == "")// 添加节点
                                {
                                    XmlNode newNode;
                                    newNode = xmlDoc.CreateNode("element", Node, "");//创建节点
                                    newNode.InnerText = Value;//给节点赋值
                                    xe.AppendChild(newNode);//把节点添加到doc
                                    xmlDoc.Save(filepath);
                                    ReStr = "9999999999999999999";
                                }
                            }
                        }
                    }
                }
                return ReStr;
            }
            catch
            {
                return "9999999999999999990";
            }

        }

        /// <summary>
        /// 文件名
        /// </summary>
        /// <returns></returns>
        public static string newFileName()
        {
            string str = "";
            System.Text.StringBuilder s = new System.Text.StringBuilder();
            s.Append(DateTime.Now.Year.ToString());
            s.Append(DateTime.Now.Month.ToString());
            s.Append(DateTime.Now.Day.ToString());
            s.Append(DateTime.Now.Hour.ToString());
            s.Append(DateTime.Now.Minute.ToString());
            s.Append(DateTime.Now.Second.ToString());
            s.Append(AMG.Common.Rand.Str(5));
            str = s.ToString();
            return str;
        }
        /// <summary>
        /// 转换为金钱字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ParseMoney(int money)
        {
            string str = money.ToString();
            char[] s = ConvertStr(str).ToCharArray();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < s.Length; i++)
            {
                sb.Append(s[i]);
                if ((i + 1) % 3 == 0)
                {
                    sb.Append(",");
                }
            }
            string ts = ConvertStr(sb.ToString());
            if (ts.StartsWith(","))
            {
                ts = ts.Substring(1);
            }
            ts = "¥" + ts;
            return ts;
        }
        /// <summary>
        /// 字符串反串
        /// </summary>
        /// <param name="str">字符串</param>
        /// <returns></returns>
        public static string ConvertStr(string str)
        {
            StringBuilder sb = new StringBuilder();
            char[] s = str.ToCharArray();
            for (int i = s.Length - 1; i >= 0; i--)
            {
                sb.Append(s[i]);
            }
            return sb.ToString();
        }
        /// <summary>
        /// 判断字符串是否全为中文
        /// </summary>
        /// <param name="words"></param>
        /// <returns></returns>
        public static bool WordsIScn(string s)
        {
            for (int i = 0; i < s.Length; i++)
            {
                Regex rx = new Regex("^[\u4e00-\u9fa5]$");
                if (!rx.IsMatch(s[i].ToString()))
                {
                    return false; 
                }
            }
            return true;
        }
        /// <summary>
        /// 写日志
        /// </summary>
        /// <param name="text"></param>
        public static void SetComGameLog(string text)
        {
            StreamWriter sw;
            string logName = "ComGameLog.txt";
            string filePath = "D:\\";
            try
            {
                string webPath = HttpContext.Current.Server.MapPath("/");
                filePath = webPath + "\\" + logName;
            }
            catch
            {
                filePath = filePath + logName;
            }
            if (File.Exists(filePath))
            {
                sw = System.IO.File.AppendText(filePath);
            }
            else
            {
                sw = File.CreateText(filePath);
            }
            sw.WriteLine(text);
            sw.Close();
        }
    }
}
